package com.cup.common.encryption;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.Charsets;

public class AESUtils {

    /**
	 * 加密
	 * @param content 需要加密的内容
	 * @param password 加密密钥
	 * @return
	 */
	public static byte[] encrypt(String content, String password) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = content.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), "AES");
	        cipher.init(Cipher.ENCRYPT_MODE, keyspec);//使用加密模式初始化 密钥
	        byte[] encrypt = cipher.doFinal(plaintext); //按单部分操作加密或解密数据，或者结束一个多部分操作。

	        return encrypt;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 加密
	 * @param content 需要加密的内容
	 * @param password 加密密钥
	 * @return
	 */
	public static String encryptToString(String content, String password) {
		byte[] aesBytes = encrypt(content, password);
		//Base64加密
		String encryptedString = Base64Utils.base64Encode(aesBytes);
		return encryptedString;
	}

	/**
	 * 解密
	 * @param content 待解密内容
	 * @param password 解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String password) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), "AES");
	        cipher.init(Cipher.DECRYPT_MODE, keyspec);//使用解密模式初始化 密钥
	        byte[] decrypt = cipher.doFinal(content);
	        return decrypt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
	}

	/**
	 * 解密
	 * @param content 待解密内容
	 * @param password 解密密钥
	 * @return
	 */
	public static String decryptFromString(String content, String password) {
		//Base64加密
		byte[] aesBytes = Base64Utils.base64Decode(content);
		return new String(decrypt(aesBytes, password), Charsets.UTF_8);
	}
	
}
